package models

import (
	"ginim/utils"
	"gorm.io/gorm"
)

type Community struct {
	gorm.Model
	Name        string `json:"name"`
	OwnerId     uint   `json:"owner_id"`
	Avatar      string `json:"avatar"`
	Description string `json:"description"`
}

func (t *Community) TableName() string {
	return "community"
}

func CreateCommunity(community Community) (int, string) {
	transaction := utils.DB.Begin()
	// 事务开始后，无论什么异常都会rollback
	defer func() {
		if r := recover(); r != nil {
			transaction.Rollback()
		}
	}()

	if len(community.Name) == 0 {
		return -1, "群名称不能为空"
	}

	if community.OwnerId == 0 {
		return -1, "请先登录"
	}

	if err := utils.DB.Create(&community).Error; err != nil {
		transaction.Rollback()
		return -1, "创建失败"
	}

	contact := Contact{}
	contact.OwnerId = community.OwnerId
	contact.TargetId = community.ID
	contact.Type = 2
	if err := utils.DB.Create(&contact).Error; err != nil {
		transaction.Rollback()
		return -1, "创建失败"
	}

	transaction.Commit()
	return 0, "创建成功"
}

func FindCommunityList(ownerId uint) []Community {
	contacts := make([]Contact, 0)
	ids := make([]uint64, 0)
	utils.DB.Where("owner_id = ? and type = 2", ownerId).Find(&contacts)
	for _, v := range contacts {
		ids = append(ids, uint64(v.TargetId))
	}

	communityList := make([]Community, 0)
	utils.DB.Where("id in ?", ids).Find(&communityList)
	return communityList
}

func CommunityJoin(userId uint, data string) (int, string) {
	community := Community{}
	utils.DB.Where("id = ? or name = ?", data, data).Find(&community)
	if community.Name == "" {
		return -1, "该群不存在"
	}

	contact := Contact{}
	utils.DB.Where("owner_id = ? and target_id = ? and type = 2", userId, data).Find(&contact)

	if !contact.CreatedAt.IsZero() {
		return -1, "已经在群聊中"
	}

	contact.OwnerId = userId
	contact.Type = 2
	contact.TargetId = community.ID
	utils.DB.Create(&contact)
	return 0, "加入群聊成功"
}
